/*
 * $Id$
 *
 * Copyright ( c ) 2014 XuNuo Corporation. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of XuNuo
 * Corporation ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with XuNuo Corporation or a XuNuo
 * authorized reseller (the "License Agreement"). XuNuo may make changes to the
 * Confidential Information from time to time. Such Confidential Information may
 * contain errors.
 *
 * EXCEPT AS EXPLICITLY SET FORTH IN THE LICENSE AGREEMENT, XuNuo DISCLAIMS ALL
 * WARRANTIES, COVENANTS, REPRESENTATIONS, INDEMNITIES, AND GUARANTEES WITH
 * RESPECT TO SOFTWARE AND DOCUMENTATION, WHETHER EXPRESS OR IMPLIED, WRITTEN OR
 * ORAL, STATUTORY OR OTHERWISE INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A
 * PARTICULAR PURPOSE. XuNuo DOES NOT WARRANT THAT END USER'S USE OF THE
 * SOFTWARE WILL BE UNINTERRUPTED, ERROR FREE OR SECURE.
 *
 * XuNuo SHALL NOT BE LIABLE TO END USER, OR ANY OTHER PERSON, CORPORATION OR
 * ENTITY FOR INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL
 * DAMAGES, OR DAMAGES FOR LOSS OF PROFITS, REVENUE, DATA OR USE, WHETHER IN AN
 * ACTION IN CONTRACT, TORT OR OTHERWISE, EVEN IF XuNuo HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES. XuNuo' TOTAL LIABILITY TO END USER SHALL NOT
 * EXCEED THE AMOUNTS PAID FOR THE XuNuo SOFTWARE BY END USER DURING THE PRIOR
 * TWELVE (12) MONTHS FROM THE DATE IN WHICH THE CLAIM AROSE.  BECAUSE SOME
 * STATES OR JURISDICTIONS DO NOT ALLOW LIMITATION OR EXCLUSION OF CONSEQUENTIAL
 * OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO END USER.
 *
 * Copyright version 2.0
 */
package com.th.supcom.pds.outdrugreturnapply.client.widget;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.th.supcom.pds.common.client.commom.PdsAuditPrescServiceFactory2;
import com.th.supcom.pds.common.client.model.PdsSupplyDetailModel;
import com.th.supcom.pds.common.client.model.PdsSupplyModel;
import com.th.supcom.pds.common.utils.ClientUtils;
import com.th.supcom.pds.internal.client.model.PatientInfoModel;
import com.th.supcom.pds.outdrugreturnapply.client.common.PdsSupplyResultModel;
import com.th.supcom.pds.outdrugreturnapply.client.service.OutDrugReturnApplyRpcAsync;

/**
 * 门诊退药Action
 * 
 * @author yzhang
 */
/**
 *
 */
public class OutDrugReturnApplyAction
{
    private OutDrugReturnApplyMainPanel m_mainPanel;
    private OutDrugReturnApplyFields m_fields;
    private OutDrugReturnApplyMasterGridPanel m_masterGridPanel;
    private OutDrugReturnApplyDetailGridPanel m_detailGridPanel;
    private List <PdsSupplyResultModel> m_pdsSupplyResultModels;

    private final static OutDrugReturnApplyRpcAsync S_OUT_RETURN_RPC_ASYNC = PdsAuditPrescServiceFactory2.getOutDrugReturnApplyService ();

    /**
     * 构造函数
     */
    public OutDrugReturnApplyAction ()
    {

    }

    /**
     * 根据条件查询患者信息已经可退药品信息
     * 
     * @param conditionMap
     */
    public void findDrugReturnInfo (Map <String, Object> conditionMap)
    {
        if (conditionMap.get ("patientId") == null && conditionMap.get ("prescNo") == null)
        {
            ClientUtils.alertMessageBox ("所输入患者ID或处方号不能同时为空！", conditionMap.get ("prescNo") == null ? m_fields.getPrescNoField () : m_fields.getPatiIdField ());
            return;
        }
        mask ();
        S_OUT_RETURN_RPC_ASYNC.findOutDrugReturnInfo (conditionMap, new AsyncCallback <List <PdsSupplyResultModel>> ()
        {
            @Override
            public void onSuccess (List <PdsSupplyResultModel> result)
            {
                m_masterGridPanel.getGrid ().getStore ().removeAll ();
                m_detailGridPanel.getGrid ().getStore ().removeAll ();
                m_pdsSupplyResultModels = result;
                setPatientInfo (result.get (0).getPatientInfoModel ());
                m_fields.getPatiTypeField ().setValue (result.get (0).getPdsSupplyModel ().getPrescSourceName ());
                for (PdsSupplyResultModel pdsSupplyResultModel : result)
                {
                    m_masterGridPanel.getGrid ().getStore ().add (pdsSupplyResultModel.getPdsSupplyModel ());
                }
                m_masterGridPanel.getCheckmodel ().select (0, true);
                unMask ();
            }

            @Override
            public void onFailure (Throwable caught)
            {
                unMask ();
                ClientUtils.alertMessageBox (caught.getMessage (), null);
            }
        });
    }

    /**
     * 做退药操作
     */
    public void doDrugReturn ()
    {
        List <PdsSupplyDetailModel> pdsSupplyDetailModels = m_detailGridPanel.getModels ();

        if (pdsSupplyDetailModels == null || pdsSupplyDetailModels.isEmpty ())
        {
            ClientUtils.alertMessageBox ("没有要退的药品信息，请重试！", m_fields.getMedicareCardField ());
            return;
        }
        PdsSupplyResultModel pdsSupplyResultModel = new PdsSupplyResultModel ();
        PdsSupplyModel pdsSupplyModel = m_masterGridPanel.getCheckmodel ().getSelectedItem ();
        List <PdsSupplyDetailModel> drugDetailModels = getDrugDetailModels (pdsSupplyDetailModels, pdsSupplyModel);
        if (drugDetailModels.isEmpty ())
        {
            ClientUtils.alertMessageBox ("没有填写退药数量，请重试！", m_fields.getMedicareCardField ());
            return;
        }
        PatientInfoModel patientInfoModel = m_pdsSupplyResultModels.get (0).getPatientInfoModel ();
        pdsSupplyResultModel.setPatientInfoModel (patientInfoModel);
        pdsSupplyResultModel.setPdsSupplyModel (pdsSupplyModel);
        pdsSupplyResultModel.setPdsSupplyDetailModels (drugDetailModels);
        pdsSupplyResultModel.setOperatorCode ("666666");
        pdsSupplyResultModel.setOperatorName ("李刚");
        S_OUT_RETURN_RPC_ASYNC.doDrugReturn (pdsSupplyResultModel, new AsyncCallback <Void> ()
        {

            @Override
            public void onFailure (Throwable caught)
            {
                clearData ();
                ClientUtils.alertMessageBox (caught.getMessage (), m_fields.getMedicareCardField ());

            }

            @Override
            public void onSuccess (Void result)
            {
                clearData ();
                ClientUtils.alertMessageBox ("退药申请成功！", m_fields.getMedicareCardField ());
            }
        });
    }

    public void clearData ()
    {
        m_pdsSupplyResultModels = null;
        m_masterGridPanel.getStore ().removeAll ();
        m_detailGridPanel.getStore ().removeAll ();
        m_fields.getBedNoField ().setValue (null);
        m_fields.getBeginField ().setValue (null);
        m_fields.getBirthDateField ().setValue (null);
        m_fields.getChargeTypeName ().setValue (null);
        m_fields.getDeptAdmissionDateField ().setValue (null);
        m_fields.getDeptAdmissionDays ().setValue (null);
        m_fields.getDeptAdmissionNameField ().setValue (null);
        m_fields.getEndField ().setValue (null);
        m_fields.getMedicareCardField ().setValue (null);
        m_fields.getPatiIdField ().setValue (null);
        m_fields.getPatiIdWatchField ().setValue (null);
        m_fields.getPatiNameField ().setValue (null);
        m_fields.getPatiTypeField ().setValue (null);
        m_fields.getPrepaidField ().setValue (null);
        m_fields.getPrescNoField ().setValue (null);
        m_fields.getSexField ().setValue (null);
        m_fields.getWatchTimes ().setValue (null);
    }

    /**
     * 获得明细表格中药退的数据
     * 
     * @param pdsSupplyDetailModels
     * @return
     */
    private List <PdsSupplyDetailModel> getDrugDetailModels (List <PdsSupplyDetailModel> pdsSupplyDetailModels, PdsSupplyModel pdsSupplyModel)
    {
        List <PdsSupplyDetailModel> drugReturnModels = new ArrayList <PdsSupplyDetailModel> ();
        Double totalSum = 0.0;
        for (PdsSupplyDetailModel pdsSupplyDetailModel : pdsSupplyDetailModels)
        {
            if (pdsSupplyDetailModel.getReturnQty () == null || pdsSupplyDetailModel.getReturnQty () == 0)
            {
                continue;
            }
            pdsSupplyDetailModel.setCosts (pdsSupplyDetailModel.getReturnQty () * pdsSupplyDetailModel.getPackagePrice ());
            totalSum += pdsSupplyDetailModel.getCosts ();
            drugReturnModels.add (pdsSupplyDetailModel);
        }
        pdsSupplyModel.setAmountSuggest (totalSum);
        return drugReturnModels;
    }

    private void setPatientInfo (PatientInfoModel patientInfoModel)
    {
        m_fields.getPatiIdWatchField ().setValue (patientInfoModel.getPatiId ());
        m_fields.getSexField ().setValue (patientInfoModel.getSex ());
        m_fields.getBirthDateField ().setValue (patientInfoModel.getBirthDate ());
        m_fields.getPrepaidField ().setValue (patientInfoModel.getBalance ());
        m_fields.getChargeTypeName ().setValue (patientInfoModel.getChargeType ());
        m_fields.getWatchTimes ().setValue (patientInfoModel.getVisitId ());
        m_fields.getDeptAdmissionDateField ().setValue (patientInfoModel.getVisitBeginDates ());
        m_fields.getDeptAdmissionNameField ().setValue (patientInfoModel.getDeptName ());
    }

    /**
     * 当点击主记录表格处方时 请领明细表格相应弹出或隐藏内容
     * 
     * @param selectedModel
     */
    public void doSelectedChange (PdsSupplyModel selectedModel)
    {
        if (selectedModel == null)
        {
            m_detailGridPanel.getGrid ().getStore ().removeAll ();
            return;
        }
        if (m_pdsSupplyResultModels == null || m_pdsSupplyResultModels.isEmpty ())
        {
            return;
        }
        final List <PdsSupplyDetailModel> applyDetails = getDetailSelected (selectedModel, m_pdsSupplyResultModels);
        m_detailGridPanel.getGrid ().getStore ().removeAll ();
        m_detailGridPanel.getGrid ().getStore ().add (applyDetails);
    }

    /**
     * 获得选中主记录对应的所有明细记录
     * 
     * @return
     */
    private List <PdsSupplyDetailModel> getDetailSelected (final PdsSupplyModel selectModel, final List <PdsSupplyResultModel> modelList)
    {
        for (PdsSupplyResultModel pdsSupplyResultModel : modelList)
        {
            if (selectModel.getPrescNo ().equals (pdsSupplyResultModel.getPdsSupplyModel ().getPrescNo ()))
            {
                return pdsSupplyResultModel.getPdsSupplyDetailModels ();
            }
        }
        return null;
    }

    /**
     * 设置 主面板
     * 
     * @param mainPanel
     */
    public void setMainPanel (OutDrugReturnApplyMainPanel mainPanel)
    {
        m_mainPanel = mainPanel;
    }

    /**
     * 设置 文本输入框
     * 
     * @param fields
     */
    public void setFields (OutDrugReturnApplyFields fields)
    {
        m_fields = fields;
    }

    /**
     * 设置 主记录表格
     * 
     * @param masterGridPanel
     */
    public void setMasterGridPanel (OutDrugReturnApplyMasterGridPanel masterGridPanel)
    {
        m_masterGridPanel = masterGridPanel;
    }

    /**
     * 设置 明细记录表格
     * 
     * @param detailGridPanel
     */
    public void setDetailGridPanel (OutDrugReturnApplyDetailGridPanel detailGridPanel)
    {
        m_detailGridPanel = detailGridPanel;
    }

    private void mask ()
    {
        m_mainPanel.mask ("正在为您加载……");
    }

    private void unMask ()
    {
        m_mainPanel.unmask ();
    }

    /** 提交路径. */
    public static final String SCC_BRANCH = "$URL$";

    /** 提交日期. */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";

    /** 最终修改人员. */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";

    /** 最终版本号. */
    public static final String SCC_REVISION = "$Revision$";
}
